<?php
class Services_Ebay_Feedback extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'services_ebay_feedback',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


	/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function getFeedback($shop_ids)
	{
		$wrong_feedback = array();
		foreach ($shop_ids as $s)
		{
			$shop_feedback = array();
			$token = Shop_API_Ebay::find('shop_id=?', $s)->asArray()->getOne();
			if ($token)
			{
				$ps = 200;
				$cp = 0;
				$total_entries = 1;
				while ($ps * $cp < $total_entries)
				{
					$cp++;
					$header = array(
						'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
						'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
						'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
						'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
						'X-EBAY-API-SITEID:0',
						'X-EBAY-API-CALL-NAME:GetFeedback'
					);
					$xml = '<?xml version="1.0" encoding="utf-8"?>';
					$xml .='<GetFeedbackRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
					$xml .=  '<RequesterCredentials>';
					$xml .=  '  <eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
					$xml .=  '</RequesterCredentials>';
					$xml .=  '<Pagination>';
					$xml .=    '<EntriesPerPage>' . $ps . '</EntriesPerPage>';
					$xml .=    '<PageNumber>' . $cp . '</PageNumber>';
					$xml .=  '</Pagination>';
					$xml .=  '<DetailLevel>ReturnAll</DetailLevel>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.CommentingUser</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.CommentingUserScore</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.CommentText</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.CommentTime</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.CommentType</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.FeedbackResponse</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.ItemID</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.Role</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.FeedbackID</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.FeedbackDetail.TransactionID</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackDetailArray.Feedbackdetail.ItemPrice</OutputSelector>';
					$xml .=  '<OutputSelector>FeedbackSummary.TotalFeedbackPeriodArray.FeedbackPeriod</OutputSelector>';
					$xml .='</GetFeedbackRequest>';
					$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetFeedback');
					if ($result['ack'] == SUCCESS)
					{
						$response = simplexml_load_string($result['data']);
						if ($response->Ack == 'Success')
						{
							$current_feedback = Helper_BSS_XML::ebayXMLToFeedbackArray($s, $response);
							$shop_feedback = array_merge($shop_feedback, $current_feedback['feedback']);
							$total_entries = $current_feedback['total_entries'];
						}
					}
					else
					{
						return array('ack' => FAILURE, 'message' => $result['message']);
					}
				}
				$import_result = Services_Ebay_Feedback::import($shop_feedback);
				$wrong_feedback = array_merge($wrong_feedback, $import_result['wrong_feedback']);
			}
		}
		if ($wrong_feedback)
		{
			$message = '在 ' . CURRENT_DATETIME . " 的时候，\n";
			$message .= '在获取Ebay交易评论并导入数据时，交易评论ID号为：' . implode('；', $wrong_feedback) . '；在数据保存时content字段有异常';
			Helper_BSS_Normal::sendMail('获取ebay交易评论并导入数据时出现异常的交易评论', $message, 'group3');
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function import($feedbacks)
	{
		set_time_limit(0);
		$wrong_feedback = array();
		foreach ($feedbacks as $f)
		{
			$feedback = Services_Ebay_Feedback::find('feedback_id=? and shop_id=?', $f['feedback_id'], $f['shop_id'])->getOne();
			if (empty($feedback['id']))
			{
				$where = 'sales_order_item.shop_transaction_id=\'' . $f['transaction_id'] . '\' and sales_order_item.shop_item_id=\'' . $f['shop_item_id'] . '\' and sales_order.trash_status=' . Q::ini('custom_flag/sales_order_trash_status/normal/value');
				$order_info = Sales_Order_Item::find($where)
					->joinLeft('sales_order', 'sales_time, shipped_time, shipping_method', 'sales_order.id=sales_order_item.sales_order_id')
					->joinLeft('sales_order_customer_info', 'country', 'sales_order_customer_info.sales_order_id=sales_order.id')
					->order('sales_order.id desc')->asArray()->getAll();
				$feedback = new Services_Ebay_Feedback();
				$feedback->feedback_id = $f['feedback_id'];
				$feedback->shop_id = $f['shop_id'];
				$feedback->shop_item_id = $f['shop_item_id'];
				$feedback->transaction_id = $f['transaction_id'];
				$feedback->currency_id = $f['currency_id'];
				$feedback->item_price = $f['item_price'];
				$feedback->user = $f['user'];
				$feedback->left_role = $f['left_role'];
				$feedback->product_basic_id = ($order_info ? (count($order_info) > 1 ? 0 : $order_info[0]['product_basic_id']) : NULL);
				$feedback->sales_order_id = isset($order_info[0]['sales_order_id']) ? $order_info[0]['sales_order_id'] : NULL;
				$feedback->sales_time = isset($order_info[0]['sales_time']) ? $order_info[0]['sales_time'] : NULL;
				$feedback->shipped_time = isset($order_info[0]['shipped_time']) ? $order_info[0]['shipped_time'] : NULL;
				$feedback->shipping_method = isset($order_info[0]['shipping_method']) ? $order_info[0]['shipping_method'] : NULL;
				$feedback->country = isset($order_info[0]['country']) ? $order_info[0]['country'] : NULL;
			}
			$feedback->score = $f['score'];
			$feedback->type = $f['type'];
			$feedback->content = $f['content'];
			$feedback->create_time = $f['create_time'];
			$feedback->response = $f['response'];
			$feedback->update_time = CURRENT_DATETIME;
			try
			{
				$feedback->save();
			}
			catch (Exception $ex)
			{
				$feedback->content = '';
				$feedback->content_flag = Q::ini('custom_flag/services_ebay_feedback_content_flag/abnormal/value');
				$feedback->save();
				$wrong_feedback[] = $f['feedback_id'];
			}
		}
		return array('ack' => SUCCESS, 'message' => '', 'wrong_feedback' => $wrong_feedback);
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'services_ebay_feedback.*',
			'product_basic.number as product_number, product_basic.name as product_name',
			'shop.name as shop_name',
			'currency.symbol as currency_symbol',
			'shipping_method.name as shipping_method_name'
		);
		$where = Services_Ebay_Feedback::buildSearchWhere($condition);
		$select = Services_Ebay_Feedback::find($where)
			->joinLeft('product_basic', '', 'product_basic.id=services_ebay_feedback.product_basic_id')
			->joinLeft('shop', '', 'services_ebay_feedback.shop_id=shop.id')
			->joinLeft('currency', '', 'currency.id=services_ebay_feedback.currency_id')
			->joinLeft('shipping_method', '', 'shipping_method.id=services_ebay_feedback.shipping_method')
			->setColumns($columns)->order('services_ebay_feedback.create_time desc');
		if ($cp == 0 && $ps == 0)
		{
			$pagination = array();
		}
		else
		{
			$select->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$feedback = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $feedback,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if ( ! empty($condition['ids']))
		{
			$where .= ' and services_ebay_feedback.id in (\'' . implode('\',\'', $condition['ids']) . '\')';
		}
		if ( ! empty($condition['begin_create_time']))
		{
			$where .= ' and services_ebay_feedback.create_time>=\'' . $condition['begin_create_time'] . '\'';
		}
		if ( ! empty($condition['end_create_time']))
		{
			$where .= ' and services_ebay_feedback.create_time<=\'' . $condition['end_create_time'] . '23:59:59\'';
		}
		if ( ! empty($condition['shop_user_mapping']))
		{
			$shop_id = Shop_User_Mapping::getShopIdByUserId();
			$where .= ' and services_ebay_feedback.shop_id in (\'' . implode('\',\'', $shop_id) . '\')';
		}
		if (isset($condition['shop_ids']))
		{
			$where .= ' and services_ebay_feedback.shop_id in (\'' . implode('\',\'', $condition['shop_ids']) . '\')';
		}
		if ( ! empty($condition['country']))
		{
			$where .= ' and services_ebay_feedback.country=\'' . $condition['country'] . '\'';
		}
		if ( ! empty($condition['user']))
		{
			$where .= ' and services_ebay_feedback.user=\'' . $condition['user'] . '\'';
		}
		if ( ! empty($condition['shop_item_id']))
		{
			$where .= ' and services_ebay_feedback.shop_item_id=\'' . $condition['shop_item_id'] . '\'';
		}
		if ( ! empty($condition['transaction_id']))
		{
			$where .= ' and services_ebay_feedback.transaction_id=\'' . $condition['transaction_id'] . '\'';
		}
		if ( ! empty($condition['type']))
		{
			$type_filter = '0';
			foreach (Q::ini('custom_flag/services_ebay_feedback_type') as $t)
			{
				if (isset($condition['type'][$t['value']]) && $condition['type'][$t['value']] == $t['value'])
				{
					$type_filter .= ' or services_ebay_feedback.type=\'' . $t['value'] . '\'';
				}
			}
			$where .= ' and (' . $type_filter . ')';
		}
		if ( ! empty($condition['begin_shipped_time']))
		{
			$where .= ' and services_ebay_feedback.shipped_time>=\'' . $condition['begin_shipped_time'] . '\'';
		}
		if ( ! empty($condition['end_shipped_time']))
		{
			$where .= ' and services_ebay_feedback.shipped_time<=\'' . $condition['end_shipped_time'] . '23:59:59\'';
		}
		if ( ! empty($condition['shipping_method']))
		{
			$shipping_method_filter = '0';
			$shipping_method = Shipping_Method::find()->asArray()->getAll();
			foreach ($shipping_method as $sm)
			{
				if (isset($condition['shipping_method'][$sm['id']]) && $condition['shipping_method'][$sm['id']] == $sm['id'])
				{
					$shipping_method_filter .= " or services_ebay_feedback.shipping_method='{$sm['id']}'";
				}
			}
			$where .= " and ($shipping_method_filter)";
		}
		return $where;
	}
}